/**
 * 
 * 此处监听消息列表的变化进行对websocket进行数据的发送
 */

import { stateType } from "@/store"
import { useEffect } from "react"
import { useSelector } from "react-redux"
type SendMsgSocketType = {
    sendMsg: (data: any) => void
}

const useSendMsgSocket = (props: SendMsgSocketType) => {
    const msgList = useSelector((state: stateType) => state.MessageReducer) 
    const { chatid } = useSelector((state: stateType) => state.CustomerInfoReducer)
    const {chatid:customerchartid} = useSelector((state:stateType)=>state.ServiceReducer)
    const { sendMsg } = props
    useEffect(() => {
        if(msgList.length === 0) return
        const latestMsg = msgList[msgList.length - 1]
        if (latestMsg?.sendid === chatid) {/**保证发送人的消息才会触发 */
            const { info } = latestMsg
            let infovalue:any = {
                "type": "MSG",
                "receiveChatId": customerchartid
            }
            //如果是文字信息
            if(info.type === 'text'){
                infovalue.content = {
                    type: info.type,
                    info: info.value
                }
            }else if(info.type === 'image' && info.isSuccess && info.imagerealurl ){
                infovalue.content = {
                    type: info.type,
                    info: info.imagerealurl
                }
            }
            
            sendMsg(infovalue)
        }
    }, [msgList])

}

export default useSendMsgSocket